package com.kuang.controller;

import com.kuang.dao.DepartmentDao;
import com.kuang.dao.EmployeeDao;
import com.kuang.pojo.Department;
import com.kuang.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Controller
@RequestMapping("/Employee")
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;

    @GetMapping("/selectAll")
    public String selectAll(Model model) {
        Collection<Employee> employees = employeeDao.getAllEmp();
        model.addAttribute("emps", employees);
        return "/employee/list";
    }

    @GetMapping("/toAdd")
    public String toAdd(Integer id, Model model) {
        List<Department> department = new ArrayList<>();
        Department dept = departmentDao.getDepartmentById(id);
        department.add(dept);
        model.addAttribute("departments", department);
        return "/employee/add";
    }

    @RequestMapping("/add")
    public String add(Model model, Employee employee) {
        employeeDao.saveEmp(employee);
        return "/employee/list";
    }

    @GetMapping("/toUpdate")
    public String toUpdate(Integer id, Model model) {
        // 获取部门
        List<Department> department = new ArrayList<>();
        Department dept = departmentDao.getDepartmentById(id);
        department.add(dept);
        model.addAttribute("departments", department);

        // 获取雇员
        Employee employee = employeeDao.getEmployeeById(id);
        model.addAttribute("emp", employee);
        return "/employee/update";
    }

    // 删除员工
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id) {
        employeeDao.deleteEmployeeById(id);
        return "/employee/list";
    }


}
